package donajurema;

import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.SWT;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ColumnPixelData;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.jface.databinding.swt.SWTObservables;
import org.eclipse.jface.databinding.viewers.ViewersObservables;
import org.eclipse.jface.layout.TableColumnLayout;
import org.eclipse.core.databinding.observable.Realm;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;

import donajurema.model.Product;
import donajurema.model.ProductList;
import donajurema.model.Units;

import org.eclipse.core.databinding.beans.BeansObservables;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.jface.viewers.ComboViewer;
import org.eclipse.core.databinding.observable.value.IObservableValue;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Table;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.wb.swt.SWTResourceManager;
import org.eclipse.swt.graphics.Point;


/**
 * Dona Jurema - easy shopping
 * A simple program that allows an user to maintain a product database and a shopping cart 
 * @author      Felipe Cavalcanti
 * @version     1.1
 * @since       1.6
 */
public class Form1
{
	protected Shell	shlDonaJurema;
	ProductList productDatabase = new ProductList("Products.xml");
	private Text textName;
	private ComboViewer comboViewer; 
	Product newProduct = new Product();
	TableLabelProvider tableLabelProvider = new TableLabelProvider();
	private Table table;
	TableViewer tableViewer;
	/**
	 * Launch the application.
	 * @param args
	 */
	public static void main(String[] args)
	{
		Display display = Display.getDefault();
		
		Realm.runWithDefault(SWTObservables.getRealm(display), new Runnable() {
			public void run() {
				try
				{
					Form1 window = new Form1();
					window.open();
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Open the window.
	 */
	public void open()
	{
		Display display = Display.getDefault();
		

		createContents();
		shlDonaJurema.open();
		shlDonaJurema.layout();
		while (!shlDonaJurema.isDisposed())
		{
			if (!display.readAndDispatch())
			{
				display.sleep();
			}
		}
	}
	
	private void delProduct()
	{
		if (!tableViewer.getSelection().isEmpty()) 
		{
			IStructuredSelection selection = (IStructuredSelection)tableViewer.getSelection();
			Product p = (Product)selection.getFirstElement();
			productDatabase.removeProduct(p);
			tableViewer.refresh();
		}
	}
	
	private void addProduct()
	{
		Product copy = new Product(newProduct);
		productDatabase.addProduct(copy);
		tableViewer.refresh();
	}
	
	private void addOnKey(KeyEvent e)
	{
		switch (e.character) 
		{
	        case SWT.CR:
	        	addProduct();
	        	break;
	        case SWT.ESC:
	        	textName.setText("");
	        	break;
	    }
	}

	/**
	 * Create contents of the window.
	 */
	protected void createContents()
	{
		
		shlDonaJurema = new Shell();
		shlDonaJurema.setImage(SWTResourceManager.getImage(Form1.class, "/resources/visa.png"));
		shlDonaJurema.setMinimumSize(new Point(400, 300));
		shlDonaJurema.setSize(513, 535);
		shlDonaJurema.setText("Dona Jurema vai as Compras");
		shlDonaJurema.setLayout(new FillLayout(SWT.HORIZONTAL));
		
		Menu menu = new Menu(shlDonaJurema, SWT.BAR);
		shlDonaJurema.setMenuBar(menu);
		
		MenuItem mntmFile = new MenuItem(menu, SWT.CASCADE);
		mntmFile.setText("File");
		
		Menu menu_1 = new Menu(mntmFile);
		mntmFile.setMenu(menu_1);
		
		MenuItem mntmExit = new MenuItem(menu_1, SWT.NONE);
		mntmExit.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				System.exit(0);
			}
		});
		mntmExit.setText("Exit");
		
		TabFolder tabFolder = new TabFolder(shlDonaJurema, SWT.NONE);
		tabFolder.setBackground(SWTResourceManager.getColor(SWT.COLOR_WIDGET_BACKGROUND));
		
		TabItem tabItemProducts = new TabItem(tabFolder, SWT.NONE);
		tabItemProducts.setText("Products");
		
		
		
		Composite composite = new Composite(tabFolder, SWT.NONE);
		tabItemProducts.setControl(composite);
		composite.setBackground(SWTResourceManager.getColor(SWT.COLOR_WIDGET_BACKGROUND));
		GridLayout gl_composite = new GridLayout();
		gl_composite.verticalSpacing = 0;
		composite.setLayout(gl_composite);
		
		Composite composite_table = new Composite(composite, SWT.NONE);
		GridData gd_composite_table = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 2);
		gd_composite_table.heightHint = 317;
		composite_table.setLayoutData(gd_composite_table);
		TableColumnLayout layout = new TableColumnLayout();
		composite_table.setLayout(layout);
		
			tableViewer = new TableViewer(composite_table, SWT.BORDER | SWT.FULL_SELECTION);
			table = tableViewer.getTable();
			table.setSize(410, 361);
			table.addKeyListener(new KeyAdapter() {
				@Override
				public void keyPressed(KeyEvent e) 
				{
					switch (e.character) 
					{
				        case SWT.CR:
				        	addProduct();
				        	break;
				        case SWT.DEL:
				        	delProduct();
				        	break;
				        case SWT.ESC:
				        	textName.setText("");
				        	textName.setFocus();
				        	break;
				    }
					
				}
			});
			table.setLinesVisible(true);
			table.setHeaderVisible(true);
			
			TableViewerColumn tableViewerColumn = new TableViewerColumn(tableViewer, SWT.NONE);
			TableColumn tblclmnName = tableViewerColumn.getColumn();
			tblclmnName.setResizable(false);
			tblclmnName.setMoveable(true);
			tblclmnName.setWidth(300);
			tblclmnName.setText("Name");
			
			TableViewerColumn tableViewerColumn_1 = new TableViewerColumn(tableViewer, SWT.NONE);
			TableColumn tblclmnUnits = tableViewerColumn_1.getColumn();
			tblclmnUnits.setResizable(false);
			tblclmnUnits.setWidth(70);
			tblclmnUnits.setText("Units");
			
			// Table column percentage.
			layout.setColumnData( tblclmnName, new ColumnWeightData(10));
			layout.setColumnData( tblclmnUnits, new ColumnPixelData(70));
			
			Menu menu_3 = new Menu(table);
			table.setMenu(menu_3);
			
			MenuItem mntmDelete_1 = new MenuItem(menu_3, SWT.NONE);
			mntmDelete_1.setImage(SWTResourceManager.getImage(Form1.class, "/resources/del.gif"));
			mntmDelete_1.addSelectionListener(new SelectionAdapter() {
				@Override
				public void widgetSelected(SelectionEvent e) {
					delProduct();
				}
			});
			mntmDelete_1.setText("Delete");
			
			tableViewer.setContentProvider(ArrayContentProvider.getInstance());
			tableViewer.setLabelProvider(tableLabelProvider);
			tableViewer.setInput(productDatabase.getProducts());

			
			
			Group grpAddNewProduct = new Group(composite, SWT.SHADOW_ETCHED_IN);
			grpAddNewProduct.setLayout(new GridLayout(3, false));
			GridData gd_grpAddNewProduct = new GridData(SWT.FILL, SWT.BOTTOM, true, false, 1, 1);
			gd_grpAddNewProduct.minimumWidth = 200;
			gd_grpAddNewProduct.widthHint = 411;
			grpAddNewProduct.setLayoutData(gd_grpAddNewProduct);
			grpAddNewProduct.setText("Add new product");
			
			Label lblNewLabel = new Label(grpAddNewProduct, SWT.NONE);
			lblNewLabel.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1));
			lblNewLabel.setText("Name");
			
			Label lblUnit = new Label(grpAddNewProduct, SWT.NONE);
			lblUnit.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1));
			lblUnit.setText("Unit");
			new Label(grpAddNewProduct, SWT.NONE);
			
			textName = new Text(grpAddNewProduct, SWT.BORDER);
			textName.addKeyListener(new KeyAdapter() {
				@Override
				public void keyPressed(KeyEvent e) 
				{
					addOnKey(e);
				}
			});

			GridData gd_textName = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1);
			gd_textName.widthHint = 247;
			textName.setLayoutData(gd_textName);
			
			comboViewer = new ComboViewer(grpAddNewProduct, SWT.READ_ONLY);
			Combo comboUnits = comboViewer.getCombo();
			comboUnits.addKeyListener(new KeyAdapter() {
				@Override
				public void keyPressed(KeyEvent e) {
					addOnKey(e);
				}
			});
			GridData gd_comboUnits = new GridData(SWT.FILL, SWT.TOP, false, false, 1, 1);
			gd_comboUnits.widthHint = 40;
			comboUnits.setLayoutData(gd_comboUnits);
			comboViewer.setContentProvider(ArrayContentProvider.getInstance());
			comboViewer.setInput(Units.values());
			
			Button btnNewButton = new Button(grpAddNewProduct, SWT.NONE);
			btnNewButton.addMouseListener(new MouseAdapter() {
				@Override
				public void mouseDown(MouseEvent e) {
					addProduct();
				}
			});
			btnNewButton.addKeyListener(new KeyAdapter() {
				@Override
				public void keyPressed(KeyEvent e) 
				{
					addOnKey(e);
				}
			});
			GridData gd_btnNewButton = new GridData(SWT.FILL, SWT.TOP, false, false, 1, 1);
			gd_btnNewButton.widthHint = 70;
			btnNewButton.setLayoutData(gd_btnNewButton);
			btnNewButton.setText("Add");
			new Label(composite, SWT.NONE);
			
			
		
		TabItem tbtmShoppingList = new TabItem(tabFolder, 0);
		tbtmShoppingList.setText("Shopping List");
		
		TabItem tbtmCart = new TabItem(tabFolder, SWT.NONE);
		tbtmCart.setText("Cart");
	
	
		initDataBindings();
	}
	protected DataBindingContext initDataBindings() {
		DataBindingContext bindingContext = new DataBindingContext();
		//
		IObservableValue textNameObserveTextObserveWidget = SWTObservables.observeText(textName, SWT.Modify);
		IObservableValue newProductNameObserveValue = BeansObservables.observeValue(newProduct, "name");
		bindingContext.bindValue(textNameObserveTextObserveWidget, newProductNameObserveValue, null, null);
		//
		IObservableValue comboViewerObserveSingleSelection = ViewersObservables.observeSingleSelection(comboViewer);
		IObservableValue newProductUnitObserveValue = BeansObservables.observeValue(newProduct, "unit");
		bindingContext.bindValue(comboViewerObserveSingleSelection, newProductUnitObserveValue, null, null);
		//
		return bindingContext;
	}
}
